﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Composite;

namespace Infragistics.Composite.Wpf.Samples.ClockModule
{
    public partial class ClockView : UserControl, IActiveAware
    {
        ClockViewModel _clockViewModel;

        public ClockView()
        {
            InitializeComponent();

            this.Loaded += this.OnLoaded;
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            if (_clockViewModel == null)
            {
                _clockViewModel = base.DataContext as ClockViewModel;
                _clockViewModel.PropertyChanged += this.OnClockViewModelPropertyChanged;
            }

            if (_clockViewModel != null)
                _clockViewModel.Start();
        }

        void OnClockViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "CurrentTime")
                this.SecondsAreEven = DateTime.Now.Second % 2 == 0;
        }

        void OnContentPaneProxyClosed(object sender, EventArgs e)
        {
            if (_clockViewModel != null)
                _clockViewModel.Stop();
        }

        // A DataTrigger in the ContentPaneProxyStyle uses this property to determine
        // which image to show in the pane's header area.
        public bool SecondsAreEven
        {
            get { return (bool)GetValue(SecondsAreEvenProperty); }
            set { SetValue(SecondsAreEvenProperty, value); }
        }

        public static readonly DependencyProperty SecondsAreEvenProperty =
            DependencyProperty.Register(
            "SecondsAreEven", 
            typeof(bool), 
            typeof(ClockView), 
            new UIPropertyMetadata(false));

        #region IActiveAware Members
        
        bool _isActive;
        public bool IsActive
        {
            get { return _isActive; }
            set
            {
                if (value == _isActive)
                    return;

                _isActive = value;

                if (_isActive)
                    this.BringIntoView();

                this.IsActiveChanged(this, EventArgs.Empty);
            }
        }

        public event EventHandler IsActiveChanged = delegate { };

        #endregion // IActiveAware Members
    }
}